<template>
	<div>
		<div class="toolbar mt-2">
			<a-form ref="searchRef" :model="searchState" :label-col="{ style: { width: '80px' } }" @finish="current = 1; initData()">
				<a-row :gutter="20">
					<a-col :span="6">
						<a-form-item label="供应商">
							<a-input v-model:value="searchState['company_name']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="公司法人">
							<a-input v-model:value="searchState['legal_person']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="委托人">
							<a-input v-model:value="searchState['client']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="4">
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>
						</a-space>
					</a-col>
				</a-row>
			</a-form>
		</div>
		<div class="container mt-2">
			<a-table row-key="id" :row-selection="{ selectedRowKeys: selectedRowKeys, onSelect: onSelect, onSelectAll: onSelectAll }" :scroll="tableScroll" :data-source="userSource" :pagination="pagination" :loading="loading" :columns="columns" @change="initData">
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'company_name'">
						<a-space :class="{red: checkInfo(record)}">
							{{ record.company_name }}
						</a-space>
					</template>
					<template v-if="column.key === 'operation'">
						<a-space>
							<a-button v-permission="'212'" type="link" @click="showUser(record)">
								<right-outlined />查看
							</a-button>
							<a-button v-permission="'213'" type="link" @click="auditUser(record)">
								<right-outlined />审核
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>
		</div>
		<a-modal v-model:visible="show" width="1000px" title="查看供应商信息" @ok="handleOk">
			<a-form ref="formRef" v-bind="{ labelCol: { style: { width: '100px' } } }">
				<table cellspacing="0" cellpadding="0" style="width: 100%;">
					<tr>
						<td style="font-size:14px;font-weight:bold;text-align:center" colspan="3">
							<div style="margin-bottom: 10px;">基本信息</div>
						</td>
					</tr>
					<tr>
						<td colspan="3">
							<a-form-item label="公司名称" name="company_name">
								<a-input v-model:value="showData.company_name" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="供应商类别" name="supplier_type">
								<a-select v-model:value="showData.supplier_type" disabled mode="multiple" :options="supplierTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="公司性质" name="company_type">
								<a-select v-model:value="showData.company_type" disabled :options="companyTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="专业" name="major">
								<a-select v-model:value="showData.major" disabled mode="multiple" :options="majorOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3">
							<a-form-item label="经营范围" name="supplier_business_scope">
								<a-textarea v-model:value="showData.supplier_business_scope" placeholder="请输入经营范围" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">联系信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="法定代表人" name="legal_person">
								<a-input v-model:value="showData.legal_person" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="联系方式" name="contacts_tel">
								<a-input v-model:value="showData.contacts_tel" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="法人证件类型" name="legal_person_idcard_type" :rules="{required: true, message: '请输入选择法人证件类型', trigger: 'blur'}">
								<a-select v-model:value="showData.legal_person_idcard_type" placeholder="请选择证件类型" :options="idcardTypeOptions" option-filter-prop="label" disabled></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="法人证件号" name="legal_person_idcard" :rules="{required: true, message: '请输入法人证件号', trigger: 'blur'}">
								<a-input v-model:value="showData.legal_person_idcard" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件附件" name="legal_person_idcard_file_path" :rules="{required: showData.legal_person_idcard_type === 2, message:'请提交法人证件附件'}">
								<a v-if="showData.legal_person_idcard_file_path" :href="showData.legal_person_idcard_file_path" target="_blank">查看附件</a>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="是否是委托人" name="is_consignor">
								<a-switch v-model:checked="showData.is_consignor" :checked-value="1" :un-checked-value="0" disabled />
							</a-form-item>
						</td>
					</tr>
					<!--					<tr>-->
					<!--						<td>-->
					<!--							<a-form-item label="委托人">-->
					<!--								<span v-if="!showData.clients?.length" style="color:red">无</span>-->
					<!--								<span v-else style="color:red" @click="showClient(showData)">(查看)</span>-->
					<!--							</a-form-item>-->
					<!--						</td>-->
					<!--					</tr>-->
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">登录信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="登录账号" name="username">
								<a-input v-model:value="showData.username" disabled />
							</a-form-item>
						</td>
						<td colspan="2">
							<a-form-item label="登录手机号" name="mobile">
								<a-input v-model:value="showData.mobile" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">开票信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="户名" name="company_name">
								<a-input v-model:value="showData.company_name" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="社会信用代码" name="company_code">
								<a-input v-model:value="showData.company_code" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="地址" name="company_address">
								<a-input v-model:value="showData.company_address" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="电话" name="phone">
								<a-input v-model:value="showData.phone" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="开户行" name="account_bank">
								<a-input v-model:value="showData.account_bank" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="银行账号" name="company_account">
								<a-input v-model:value="showData.company_account" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">证件及有效期</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="证件类型" name="certificate_type" :rules="{ required: true, message: '请选择证件类型' }">
								<a-select v-model:value="showData.certificate_type" mode="multiple" :show-search="true" placeholder="请选择证件类型" :options="certificateTypeOptions" option-filter-prop="label" disabled></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件文件信息" name="certificate_file_path" :rules="{ required: true, message: '请上传证件文件' }">
								<a-upload v-model:file-list="showData.certificate_file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" disabled>
									<a-button>
										<template v-if="uploading">
											<loading-outlined />上传中...
										</template>
										<template v-else>
											<import-outlined />上传附件
										</template>
									</a-button>
								</a-upload>
								<span style="color:#ccc">
									提交证件文件
									<span style="color:red">PNG,JPG,DOC,EXCEL,PDF</span>文件
								</span>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件有效期" name="certificate_validity" :rules="{ required: true, message: '请输入有效期' }">
								<a-checkbox v-model:checked="showData.certificate_perpetuity" disabled @change="changeCertificatePerpetuity">长期</a-checkbox>
								<a-date-picker v-model:value="showData.certificate_validity" value-format="YYYY-MM-DD" disabled />
							</a-form-item>
						</td>
					</tr>
				</table>
			</a-form>
			<template #footer>
				<a-button key="back" @click="reject(showData)">驳回</a-button>
				<a-button v-show="toAudit" type="primary" :loading="auditLoading" @click="pass(showData)">通过</a-button>
			</template>
		</a-modal>
		<a-modal v-model:visible="rejectInfo.show" :loading="rejectInfo.loading" title="审核驳回" ok-text="确认" cancel-text="取消" @ok="rejectOk">
			<a-textarea v-model:value="rejectInfo.reason" placeholder="请输入驳回原因" :auto-size="{minRows:4, maxRows:6}"></a-textarea>
		</a-modal>
	</div>
</template>
<script setup lang="jsx">
import { computed, getCurrentInstance, reactive, ref } from "vue";
import { usePagination } from "vue-request";
import { post } from "@/utils/index.js";
import dayjs from "dayjs";
import { baseURL } from "@/utils/request.js";
import { ImportOutlined, LoadingOutlined } from "@ant-design/icons-vue";

const { proxy } = getCurrentInstance();
const searchState = reactive({});
const clientSource = ref([]);
const showData = ref({});
const show = ref(false);
const toAudit = ref(false);
const uploading = ref(false);
const certificateTypeOptions = ref([]);
const auditLoading = ref(false);
const majorOptions = [
	{
		value: 1,
		label: "劳务作业"
	},
	{
		value: 2,
		label: "专业作业"
	},
	{
		value: 3,
		label: "材料供应"
	},
	{
		value: 4,
		label: "机械租赁"
	},
	{
		value: 5,
		label: "服务提供"
	},
	{
		value: 6,
		label: "回收处理"
	}
]

const supplierTypeOptions = [
	{
		value: 1,
		label: "生产制造单位"
	},
	{
		value: 2,
		label: "贸易单位"
	},
	{
		value: 3,
		label: "代理经销"
	},
	{
		value: 4,
		label: "服务提供"
	}
]
const companyTypeOptions = [
	{
		value: 1,
		label: "有限公司"
	},
	{
		value: 2,
		label: "股份公司"
	},
	{
		value: 3,
		label: "央企"
	},
	{
		value: 4,
		label: "国企"
	},
	{
		value: 5,
		label: "国资委"
	}
]
const idcardTypeOptions = [
	{
		value: 1,
		label: "身份证"
	},
	{
		value: 2,
		label: "其他"
	},
]
const selectedRowKeys = ref([]);
const formState = ref({
	certificate_perpetuity: false,
});
const rejectInfo = ref({
	id: null,
	show: false,
	reason: null,
})
post("dictionary", { root_id: "1039" }).then(data => {
	certificateTypeOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const handleOk = () => {
	show.value = false;
}
const pass = (company) => {
	if (!company.certificate_file_path || !company.certificate_validity || !company.certificate_type?.length) {
		return proxy.$message.error('证件信息未完善,无法审核');
	}
	if (!company.legal_person_idcard_type || !company.legal_person_idcard || (company.legal_person_idcard_type === 2 && !company.legal_person_idcard_file_path)) {
		return proxy.$message.error('证件信息未完善,无法审核');
	}
	auditLoading.value = true;
	const params = {
		id: company.id,
		status: 1,
	}
	post("user/save", params)
		.then(() => {
			proxy.$message.success("审核成功", 1).then(async () => {
				auditLoading.value = false;
				handleOk()
				initData()
			});
		})
		.catch(err => {
			proxy.$message.error(err);
			auditLoading.value = false
		});
}
const reject = (company) => {
	rejectInfo.value = {
		show: true,
		id: company.id,
		reason: null,
		loading: false,
	}
}
const rejectOk = () => {
	if (!rejectInfo.value.reason) {
		proxy.$message.error('请输入驳回原因');
	} else {
		rejectInfo.value.loading = true;
		post("user/save", {
			id: rejectInfo.value.id,
			status: -2,
			reject_reason: rejectInfo.value.reason,
		}).then(() => {
			proxy.$message.success("驳回成功", 1).then(async () => {
				rejectInfo.value.loading = false;
				rejectInfo.value.show = false;
				handleOk()
				initData()
			});
		})
			.catch(err => {
				proxy.$message.error(err);
				rejectInfo.value.loading = false
			});
	}
}
const userSource = computed(() => data.value?.data || []);
const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 60,
		align: 'center',
		fixed: "left"
	},
	{
		title: "供应商",
		dataIndex: "company_name",
		sorter: false,
		align: "center",
		width: 200,
		ellipsis: true
	},
	{
		title: "手机号",
		dataIndex: "mobile",
		sorter: false,
		align: "center",
		width: 120
	},
	{
		title: "法人",
		dataIndex: "legal_person",
		sorter: false,
		align: "center",
		width: 140
	},
	{
		title: "供应商类型",
		dataIndex: "supplier_type",
		sorter: false,
		width: 200,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			//return supplierTypeOptions.find(d => d.value === text)?.label
			return text?.split(",").map(d => {
				d = supplierTypeOptions.find(d1 => d1.value === parseInt(d))?.label
				return d;
			}).join(",")
		}
	},
	{
		title: "创建人",
		dataIndex: "opr_user",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return '注册'
		}
	},
	{
		title: "最后更新时间",
		dataIndex: "update_time",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 260,
		align: "center"
	}
];
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));
const initData = (pag, filters, sorter) => {
	pag = Object.assign({
		current: current.value,
		pageSize: pageSize.value
	}, pag || {});
	filters = { ...filters, ...searchState };

	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
const { data, loading, run, runAsync, current, pageSize, total } = usePagination(params => post("supplier", { ...params, ...searchState, status: -1 }), {
	defaultParams: [
		{
			page_size: 15
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const showClient = record => {
	post("user", { parent_id: record.id, page_size: Infinity, is_consignor: 1 }).then(({ data }) => {
		clientSource.value = data.map(d => {
			return d;
		});
	});
}
const checkInfo = (item) => {
	if (!item.company_type) return true;
	if (!item.legal_person_idcard) return true;
	if (!item.legal_person) return true;
	if (!item.company_code) return true;
	if (!item.account_bank) return true;
	if (!item.company_account) return true;
	if (!item.certificate_type) return true;
	if (!item.certificate_file_path) return true;
	if (!item.certificate_validity) return true;
	if (!item.clients.length) return true;
	return false;
}
const showUser = (record) => {
	toAudit.value = false;
	getUserInfo(record);
}
const auditUser = (record) => {
	toAudit.value = true;
	getUserInfo(record);
}
const getUserInfo = (record) => {

	show.value = true;
	const data = { ...record };
	data.major_name = "";
	data.supplier_type_name = "";

	data.company_type_name = '';
	majorOptions.forEach((d) => {
		if (d.value === data.major) {
			data.major_name = d.label;
		}
	})
	supplierTypeOptions.forEach((d) => {
		if (d.value === data.supplier_type) {
			data.supplier_type_name = d.label;
		}
	})
	companyTypeOptions.forEach((d) => {
		if (d.value === data.company_type) {
			data.company_type_name = d.label;
		}
	})
	data.supplier_type = data.supplier_type?.split(",").map(d => {
		d = parseInt(d);
		return d;
	});
	data.company_type = data.company_type?.split(",").map(d => {
		d = parseInt(d);
		return d;
	})[0];
	data.major = data.major?.split(",").map(d => {
		d = parseInt(d);
		return d;
	});
	data.certificate_type = data.certificate_type ? String(data.certificate_type).split(',').map(item => parseInt(item)) : [];
	data.certificate_perpetuity = data.certificate_validity === '9999-12-31';
	showData.value = data;
}
const onSelect = (record, selected, selectedRows, nativeEvent) => {
	if (!selected) {
		const index = selectedRowKeys.value.findIndex((d) => d === record.id);
		selectedRowKeys.value.splice(index, 1);
	} else {
		selectedRowKeys.value.push(record.id);
	}
}
const onSelectAll = (selected, selectedRows, changeRows) => {
	if (selected) {
		changeRows.forEach((v) => {
			selectedRowKeys.value.push(v.id);
		})
	} else {
		changeRows.forEach((v) => {
			const index = selectedRowKeys.value.findIndex((d) => d === v.id);
			selectedRowKeys.value.splice(index, 1);
		})
	}
}
const changeCertificatePerpetuity = () => {
	if (formState.value.certificate_perpetuity) {
		formState.value.certificate_validity = '9999-12-31'
	} else {
		formState.value.certificate_validity = dayjs(new Date()).format('YYYY-MM-DD');
		// formState.value.certificate_validity = null;
	}
}
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 250 }));
</script>